import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:moose_app/ui/screens/main/main_bottom_appbar_item.dart';
import 'package:moose_app/ui/values/values.dart';

import 'main_body.dart';

class ATHMainScreen extends StatefulWidget {
  static final String routeName = "app://main";

  @override
  _ATHMainScreenState createState() => _ATHMainScreenState();
}

class _ATHMainScreenState extends State<ATHMainScreen>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  int _currentTabIndex = 0;

  PageController _mainPageController;

  @override
  void initState() {
    _mainPageController =
        PageController(initialPage: _currentTabIndex, keepPage: true);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: ATHMainBody(
        pageController: _mainPageController,
      ),
      bottomNavigationBar: _buildBottomAppBar(),
    );
  }

  void _onItemSelected(dynamic index) {
    if (index == _currentTabIndex) return;
    setState(() {
      _currentTabIndex = index;
      _mainPageController.jumpToPage(index);
    });
  }

  Color _getBarItemColor(int index) {
    return _currentTabIndex == index ? kColorPrimary : kColor99;
  }

  List<Widget> _buildBarItems() {
    List<MainTabItem> _mainTabs = [
      MainTabItem(
        iconPath: 'assets/icons/tabbar/icon_home.svg',
        title: "首页",
      ),
      MainTabItem(
        iconPath: 'assets/icons/tabbar/icon_discovery.svg',
        title: "发现",
      ),
      MainTabItem(iconPath: "assets/icons/icon_bag.svg", title: "购物车"),
      MainTabItem(iconPath: "assets/icons/tabbar/icon_mime.svg", title: "我的")
    ];

    List<ATHMainBottomAppbarItem> items = [];
    for (int i = 0; i < _mainTabs.length; i++) {
      MainTabItem item = _mainTabs[i];

      items.add(ATHMainBottomAppbarItem(
          title: item.title,
          color: _getBarItemColor(i),
          iconPath: item.iconPath,
          press: () {
            _onItemSelected(i);
          }));
    }
    _mainTabs = null;
    return items;
  }

  Widget _buildBottomAppBar() {
    return BottomAppBar(
        shape: CircularNotchedRectangle(),
        child: Padding(
          padding: EdgeInsets.fromLTRB(0, 12.w, 0, 0),
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: _buildBarItems(),
          ),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}

class MainTabItem {
  String iconPath;

  String title;

  MainTabItem({this.iconPath, this.title});
}
